import React, { useContext, useEffect, useRef } from "react";
import { Location, useLocation } from "react-router-dom";

const LastLocationContext =
  React.createContext<Location | undefined>(undefined);

interface LastLocationProviderProps {
  lastLocation?: Location;
  children?: React.ReactNode;
}

const LastLocationProvider: React.FC<LastLocationProviderProps> = ({
  children,
}) => {
  const location = useLocation();
  const lastLocation = useRef<Location>();

  useEffect(() => {
    lastLocation.current = location;
  }, [location]);

  return (
    <LastLocationContext.Provider value={lastLocation.current}>
      {children}
    </LastLocationContext.Provider>
  );
};

export function useLastLocation() {
  return useContext(LastLocationContext);
}

export default LastLocationProvider;
